package com.example.websocket.interceptor;

import java.util.Map;

import com.alibaba.fastjson.JSON;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * @author LiYuhang
 * @version 0.1
 * @date 2023/9/20 21:41
 */
public class CustomInterceptor implements HandshakeInterceptor {
    private static final Logger log = LoggerFactory.getLogger(CustomInterceptor.class);

    /**
     * 握手前
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {
        System.out.println(request.getURI());
        // 获得请求参数
        Map<String, String> paramMap = HttpUtil.decodeParamMap(request.getURI().getQuery(),
            CharsetUtil.charset("utf-8"));
        log.info("握手开始,paramMap:{}", JSON.toJSONString(paramMap));
        String tokenId = paramMap.get("tokenId");
        if (StrUtil.isNotBlank(tokenId)) {
            // 放入属性域
            attributes.put("token", tokenId);
            System.out.println("用户 token " + tokenId + " 握手成功！");
            return true;
        }
        System.out.println("用户登录已失效");
        return false;
    }

    /**
     * 握手后
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
        Exception exception) {
        System.out.println("握手完成");
    }
}


